import {ElMessage} from 'element-plus'

const defultError = () =>{
    ElMessage({
        message: '出了点问题',
        type: 'error',
      })
}

export function get(url,success,error = defultError) {
   fetch(url, {
    method: "GET",
    mode: "cors",
    credentials: "include",
  })
  .then(res => res.json())
  .then(res => {
    success(res)
  })
  .catch(err => error())
}
export  function post_json(url,data,success,error = defultError){
        fetch(url,{
        method: "POST",
        mode: "cors",
        credentials: "include",
        headers:{
            "Content-Type": "application/json"
        },
        body : data
    })
    .then(res=>res.json())
    .then(res => {
        success(res)
    })
    .catch(err => error())
}
export function post_form(url,data,success,error = defultError){
     fetch(url,{
        method: "POST",
        mode: "cors",
        credentials: "include",
        headers:{
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body : data
    })
    .then(res=>res.json())
    .then(res => {
        success(res)
    })
    .catch(err => error())
}
export  function deLete(url,success,error = defultError){
        fetch(url,{
        method: "DELETE",
        mode: "cors",
        credentials: "include",
    })
    .then(res => res.json())
    .then(res => {
    success(res)
    })
    .catch(err => error())
}
export  function put(url,data,success,error = defultError){
        fetch(url,{
        method: "PUT",
        mode: "cors",
        headers:{
            "Content-Type": "application/json"
        },
        credentials: "include",
        body:data
    })
    .then(res=>res.json())
    .then(res => {
        success(res)
    })
    .catch(err => error())
}

/**
 * 
 * @param {number} size 
 * @param {number} page 
 * @param {Array} originList 
 * @returns 
 */
export function pagination(size,page,originList){
    if(originList === null){
        return []
    }
    let resultList = [],length = originList.length,min = (page-1)*size,max = page*size - 1
    //首先声明一个空的结果序列和原数据的长度,这个页码中最小的编号，这个页码中最大的编号
    //由于数组从0开始，如果size = 10,page = 1 那么min = (1-1)*10 = 0,max = (1*10) - 1 = 9
    //if page = 2,then min = (2-1)*10 = 10, max = (2*10) - 1 = 19
    if(length === 0){
        return resultList
    }
    //when length > max , 返回全部的size个数据
    if(length >= max){
        resultList = originList.slice(min,max+1)
        return resultList
    }
    //当数据量达不到时，返回仅有的
    if(length >= min && length < max){
        resultList = originList.slice(min)
        return resultList
    }

}